# coding=utf-8
from conf.env import (
FTP_IP,
FTP_PORT,
FTP_USER,
FTP_PASSWORD,
HSPTCD
)
from ftplib import FTP
import argparse
from loguru import logger
from datetime import datetime,timedelta
from django.utils import timezone
import os,time
from django.db import transaction
from apps.TabletInfo.models import TabletInfo
from apps.prescription.models import Prescription,Drug
from apps.website.models import Website
from op_drf.response import ErrorResponse
import xml.etree.ElementTree as ET
from xml.etree.ElementTree import Element
from conf.env import AUTO_SERVE


def writeServicelog(msg):
    '''
    服务运行日志
    '''
    log_file = "服务"+datetime.now().strftime("%Y%m%d") + ".log"
    file_path = os.path.join("logs", log_file)

    with open(file_path, "a+", encoding="utf-8") as f:
        f.write(datetime.now().strftime("%Y年%m月%d日 %H:%M:%S")+"  "+str(msg))
        f.write("\r\n")


def writelog(msg):
    '''
    写入日志文本文件
    '''
    log_file = datetime.now().strftime("%Y%m%d") + ".log"
    file_path = os.path.join("logs", log_file)

    with open(file_path, "a+", encoding="utf-8") as f:
        f.write(datetime.now().strftime("%Y年%m月%d日 %H:%M:%S")+"  "+str(msg))
        f.write("\r\n")


def writeExceptlog(excepttype,msg):
    '''
    将异常数据写入异常数据表
    '''
    from apps.data_analy.models import DataAnaly
    # logger.debug("异常")
    DataAnaly.objects.create(except_type=excepttype,except_context=msg)


def ftpconnect(host="",username="",password="",port=""):
    # 地址，用户名和密码都使用默认值参数,从配置文件中获取
    if not host:
        host = FTP_IP
    if not username:
        username = FTP_USER
    if not password:
        password = FTP_PASSWORD
    if not port:
        port = FTP_PORT


    try:
        ftp = FTP()
        ftp.connect(host,port)
    except Exception as e:
        writelog("ftp连接错误")
        return None

    try:
        ftp.login(username,password)
        return ftp
    except Exception as e:
        writelog("ftp用户名或密码错误")
        return None


# 从本地上传文件到FTP
def uploadfile(remotepath,localpath):
    # try:
    ftp = ftpconnect()
    if ftp:
        bufsize = 1024
        fp = open(localpath, "rb")
        ftp.storbinary("STOR {}".format(remotepath), fp, bufsize)
        ftp.set_debuglevel(0)
        fp.close()
        ftp.quit()
        return "1"
    else:
        writeExceptlog(2, 'FTP连接失败')
        return "0"


def atmtorad(id=None,five_minutes_ago=None):
    '''
    调用触发下发到Rad的接口
    '''
    if id:
        prescription_list = Prescription.objects.filter(is_delete=False,OrderStatus="0",pk=id)
    else:
        if five_minutes_ago:
            prescription_list = Prescription.objects.filter(is_delete=False, OrderStatus="0",create_datetime__lte=five_minutes_ago)
        else:
            prescription_list = Prescription.objects.filter(is_delete=False, OrderStatus="0")

    for prescrption_obj in prescription_list:
        drugs = Drug.objects.filter(is_delete=False, prescrption=prescrption_obj)
        if drugs:
            # 采用名称命名的文件
            file_name = prescrption_obj.PtntNm+"_"+datetime.now().strftime("%Y%m%d")+"_"+prescrption_obj.orderId+".xml"
            # 创建根目录
            root = ET.Element('OrderInfo')
            tree = ET.ElementTree(root)
            # 医院代码
            hsptcd_obj = HSPTCD
            hsptcd = Element('HsptCd')
            hsptcd.text = hsptcd_obj
            root.append(hsptcd)
            # 诊疗科室代码
            dptmptcd = Element('DptmtCd')
            dptmptcd.text = prescrption_obj.DptmtCd if prescrption_obj.DptmtCd else ""
            root.append(dptmptcd)
            # 病区代码
            wardcd = Element('WardCd')
            wardcd.text = prescrption_obj.WardCd if prescrption_obj.WardCd else ""
            root.append(wardcd)
            # 处方文件分类
            dataclsf = Element('DataClsf')
            dataclsf.text = 'N'
            root.append(dataclsf)
            # 住院I临时O,这儿需要判断
            inoutclsf = Element('InOutClsf')
            inoutclsf.text = prescrption_obj.inoutclsf if prescrption_obj.inoutclsf else ""
            root.append(inoutclsf)
            # 药方发药日期
            orderdt = Element('OrderDt')
            orderdt.text = prescrption_obj.OrderDt.strftime("%Y%m%d") if prescrption_obj.OrderDt else ""
            root.append(orderdt)
            # 药方发药具体时间
            orderdtm = Element('OrderDtm')
            sorderdtm = prescrption_obj.OrderDtm if prescrption_obj.OrderDtm else ""
            dt_orderdtm = ""
            try:
                # logger.debug(sorderdtm)
                dt_orderdtm = datetime.strptime(sorderdtm, "%Y/%m/%d %H:%M:%S")
            except:
                # dt_orderdtm = datetime.strptime(sorderdtm, "%Y-%m-%d %H:%M:%S")
                try:
                    dt_orderdtm = datetime.strptime(sorderdtm, "%Y-%m-%d %H:%M:%S")
                except:
                    logger.debug("药房发药时间异常")
            sorderdtm = dt_orderdtm.strftime("%Y%m%d%H%M%S")
            orderdtm.text = sorderdtm
            root.append(orderdtm)

            # 处方编号(唯一)
            ordernum = Element('OrderNum')
            ordernum.text = prescrption_obj.OrderNum if prescrption_obj.OrderNum else ""
            root.append(ordernum)

            # 病人床号
            roomnum = Element('RoomNum')
            roomnum.text = prescrption_obj.RoomNum if prescrption_obj.RoomNum else ""
            root.append(roomnum)

            # 病人姓名
            ptntnm = Element('PtntNm')
            ptntnm.text = prescrption_obj.PtntNm if prescrption_obj.PtntNm else ""
            root.append(ptntnm)

            # 病人ID号(唯一)，通过病人信息获取
            ptntnum = Element('PtntNum')
            ptntnum.text = prescrption_obj.PtntNum if prescrption_obj.PtntNum else prescrption_obj.PtntNm if prescrption_obj.PtntNm else ""
            root.append(ptntnum)

            # 性别
            sex = Element('Sex')
            sex.text = prescrption_obj.sex if prescrption_obj.sex else ""
            root.append(sex)

            # 医生姓名
            doctornm = Element('DoctorNm')
            doctornm.text = prescrption_obj.DoctorNm if prescrption_obj.DoctorNm else ""
            root.append(doctornm)

            # 生日 通过病人信息获取
            birthday = Element('Birthday')
            age = float(prescrption_obj.age if prescrption_obj.age else 0)
            leap_year_num = age//4
            age_years_ago = timezone.now() - timedelta(days=age*365+leap_year_num+1, hours=0, minutes=0)
            birthday.text = age_years_ago.strftime("%Y%m%d")
            root.append(birthday)

            # 病人居住地址
            ptntaddr = Element('PtntAddr')
            ptntaddr.text = ' '
            root.append(ptntaddr)

            # 病人电话号码
            ptnttel = Element('PtntTel')
            ptnttel.text = ' '
            root.append(ptnttel)

            # 病床号,必须传入
            bednum = Element('BedNum')
            bednum.text = prescrption_obj.BedNum if prescrption_obj.BedNum else ""
            root.append(bednum)

            # 药品信息(循环获取)
            drugs = Drug.objects.filter(is_delete=False,prescrption=prescrption_obj)

            for drug in drugs:
                tabletinfo_list = TabletInfo.objects.filter(tblt_cd=drug.MedCd)

                if tabletinfo_list:
                    tabletinfo_obj = tabletinfo_list[0]
                    # 自编药方直接提取
                    meditem = Element('MedItem')
                    # 药品编码,需通过药品名称查找
                    medcd = Element('MedCd')
                    medcd.text = tabletinfo_obj.tblt_cd if tabletinfo_obj.tblt_cd else ""
                    meditem.append(medcd)

                    # 药品名称
                    mednm = Element('MedNm')
                    mednm.text = tabletinfo_obj.tblt_nm if tabletinfo_obj.tblt_nm else ""
                    meditem.append(mednm)

                    # 二维码
                    mednote = Element('MedNote')
                    mednote.text = drug.MedNote if drug.MedNote else ""
                    meditem.append(mednote)

                    # 药品规格
                    medspec = Element('MedSpec')
                    medspec.text = tabletinfo_obj.tblt_spec if tabletinfo_obj.tblt_spec else ""
                    meditem.append(medspec)

                    # 药品单位
                    medunit = Element('MedUnit')
                    medunit.text = tabletinfo_obj.tblt_unit if tabletinfo_obj.tblt_unit else drug.MedUnit
                    meditem.append(medunit)

                    # 是否使用包药机
                    useatcyn = Element('UseAtcYn')
                    useatcyn.text = tabletinfo_obj.use_atm_yn if tabletinfo_obj.use_atm_yn else ""
                    meditem.append(useatcyn)

                    meditemdose = Element('MedItemDose')

                    takedays = Element('TakeDays')
                    takedays.text = str(drug.takedays)
                    meditemdose.append(takedays)
                    doselist_time = drug.doselist_time if drug.doselist_time else ""
                    dose_list = doselist_time.split(",")

                    dose_dict = {}
                    drug_dose = str(drug.doselist_dose if drug.doselist_dose else "")
                    for i in dose_list:
                        dose_dict[i]=drug_dose
                    str1 =""
                    for k,v in enumerate(dose_dict):
                        if len(str1)>0:
                            str1+=";"
                        str1 += f"{v}:"+drug_dose
                    doselist = Element('DoseList')
                    doselist.text = str1
                    meditemdose.append(doselist)

                    take_dt = drug.takedt if drug.takedt else ""
                    if take_dt:
                        take_dt = take_dt.strftime("%Y%m%d")
                    takedt = Element('TakeDt')
                    takedt.text = take_dt
                    meditemdose.append(takedt)

                    drtscd = Element('DrtsCd')
                    drtscd.text = drug.drtscd if drug.drtscd else ""
                    meditemdose.append(drtscd)
                    meditem.append(meditemdose)
                    root.append(meditem)
                else:
                    # 在药品基础库中没有信息时，按实际传递过来的形成xml文件
                    meditem = Element('MedItem')
                    # 药品编码,需通过药品名称查找
                    medcd = Element('MedCd')
                    medcd.text = drug.MedCd if drug.MedCd else ""
                    meditem.append(medcd)

                    # 药品名称
                    mednm = Element('MedNm')
                    mednm.text = drug.MedNm if drug.MedNm else ""
                    meditem.append(mednm)

                    # 二维码
                    mednote = Element('MedNote')
                    mednote.text = drug.MedNote if drug.MedNote else ""
                    meditem.append(mednote)

                    # 药品单位
                    medunit = Element('MedUnit')
                    medunit.text = drug.tblt_unit if drug.tblt_unit else ""
                    meditem.append(medunit)

                    # 药品规格
                    tblt_spec = drug.MedSpec if drug.MedSpec else ""
                    logger.debug(tblt_spec)
                    medspec = Element('MedSpec')
                    medspec.text = tblt_spec
                    meditem.append(medspec)


                    # 是否使用包药机
                    useatcyn = Element('UseAtcYn')
                    useatcyn.text = "Y"
                    meditem.append(useatcyn)
                    meditemdose = Element('MedItemDose')

                    takedays = Element('TakeDays')
                    takedays.text = str(int(drug.takedays)) if drug.takedays else ""
                    meditemdose.append(takedays)

                    doselist_time = drug.doselist_time if drug.doselist_time else ""
                    dose_list = doselist_time.split(",")

                    doselist_time = drug.doselist_time if drug.doselist_time else ""
                    dose_list = doselist_time.split(",")

                    dose_dict = {}
                    drug_dose = str(drug.doselist_dose if drug.doselist_dose else "")
                    for i in dose_list:
                        dose_dict[i] = drug_dose
                    str1 = ""
                    for k, v in enumerate(dose_dict):
                        if len(str1) > 0:
                            str1 += ";"
                        str1 += f"{v}:" + drug_dose
                    logger.debug(str1)
                    doselist = Element('DoseList')
                    doselist.text = str1
                    meditemdose.append(doselist)

                    dosenote = Element('DoseNote')
                    dosenote.text = drug.MedNote if drug.MedNote else ""
                    meditemdose.append(dosenote)

                    take_dt = drug.takedt if drug.takedt else ""
                    if take_dt:
                        take_dt = take_dt.strftime("%Y%m%d")
                    takedt = Element('TakeDt')
                    takedt.text = take_dt
                    meditemdose.append(takedt)

                    drtscd = Element('DrtsCd')
                    drtscd.text = drug.drtscd if drug.drtscd else ""
                    meditemdose.append(drtscd)
                    meditem.append(meditemdose)
                    root.append(meditem)
        # 写入文件并添加头文件说明
        global localfile
        floder_path = os.path.join("Rad","florder")
        if not os.path.exists(floder_path):
            os.makedirs(floder_path,exist_ok=True)
        try:
            localfile = os.path.join(floder_path, file_name)
            with open(localfile, 'wb') as fs:
                tree.write(fs, encoding='utf-8', xml_declaration=True)
        except Exception as e:
            logger.debug(e)
            logger.debug("读取文件错误")

        # 加事务
        with transaction.atomic():
            res_ = uploadfile(file_name,localfile)
            if res_:
                prescrption_obj.OrderStatus=res_
                prescrption_obj.save()
